/**
 ***********************************************************************************************************************
 * Copyright (c) 2020, China Mobile Communications Group Co.,Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
 * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 *
 * @file        tts_json.c
 *
 * @brief       tts json parser API
 *
 * @revision
 * Date         Author          Notes
 * 2020-11-20   OneOS Team      First Version
 ***********************************************************************************************************************
 */

#include "oneos_config.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <os_dbg_ext.h>
#include "tts_json.h"
#include "os_stddef.h"

#if 0//def PKG_USING_CJSON
#include "cJSON.h"

int tts_parse_token(char *token, char *data)
{
    cJSON *root = OS_NULL;
    cJSON *item = OS_NULL;

    root = cJSON_Parse(data);
    if (!root)
    {
        os_kprintf("error position data string: %s", data);
        return OS_FALSE;
    }

    item = cJSON_GetObjectItem(root, "refresh_token");

    sprintf(token, "%s", item->valuestring);

    cJSON_Delete(root); //释放内存
    return OS_TRUE;
}

#else

int tts_parse_token(char *token, char *data)
{
    char key[] = "refresh_token";
    int len = 4 + strlen(key) + 1;
    char search_key[len];
    snprintf(search_key, len, "\"%s\":\"", key);
    char *start = strstr(data, search_key);

    if (start == NULL) { // 没有找到
        os_kprintf("not found this token\n");
        return OS_FALSE;
    }

    start += strlen(search_key);
    char *end = strstr(start, "\"");
    // 最大可复制的string
    int copy_size = (TTS_BUF_SIZE < end - start) ? TTS_BUF_SIZE : end - start;
    snprintf(token, copy_size + 1, "%s", start);
    return OS_TRUE;
}
#endif
